﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Common;
using Jacaranda.Data;

namespace Jacaranda.Model
{
    public class DbFunction : ParameterGenerationNode
    {
        public DbFunction(string name, params object[] parameters)
        {
            Name = name;
            Parameters = parameters;
        }

        public string Name { get; private set; }

        public object[] Parameters { get; private set; }

        internal override string GenerateSql(Type propertyEntityType)
        {
            StringBuilder b = new StringBuilder();
            b.Append("dbo.").Append(Name).Append("(");

            for (int i = 0; i <= Parameters.Length - 1; i++ )
            {
                if (Parameters[i] is AbstractProperty)
                {
                    b.Append(Metadata.Type(propertyEntityType).Fields.First(field => field.PropertyName == (Parameters[i] as AbstractProperty).Name).FieldName);
                }
                else if (Parameters[i] is int || Parameters[i] is double)
                {
                    b.Append(Parameters[i]);
                }
                else
                {
                    string parameterName = "conditionParameter" + ParameterIndex + "_" + i;

                    DbParameter parameter = DataAccess.Create().CreateDbParameter();

                    parameter.ParameterName = parameterName;
                    parameter.Value = Parameters[i];

                    Command.Parameters.Add(parameter);

                    b.Append(DataAccess.Create().CreateParameterizedExpression(parameterName));
                }

                if (i < Parameters.Length - 1)
                {
                    b.Append(",");
                }
            }

            b.Append(")");
            return b.ToString();
        }
    }
}
